package com.wf.smartcomm.server.admin.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.aspectj.util.FileUtil;
import org.json.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ModelDriven;
import com.wf.smartcomm.server.apns.IApnsService;
import com.wf.smartcomm.server.apns.model.Payload;
import com.wf.smartcomm.server.bean.Advertisement;
import com.wf.smartcomm.server.bean.Image;
import com.wf.smartcomm.server.bean.ThumbImage;
import com.wf.smartcomm.server.bean.UnitMachine;
import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.bean.Video;
import com.wf.smartcomm.server.model.PushMessage;
import com.wf.smartcomm.server.push.Pusher;
import com.wf.smartcomm.server.service.AdService;
import com.wf.smartcomm.server.service.ImageService;
import com.wf.smartcomm.server.service.ThumbImageService;
import com.wf.smartcomm.server.service.UnitMachService;
import com.wf.smartcomm.server.service.UserService;
import com.wf.smartcomm.server.service.VideoService;
import com.wf.smartcomm.server.util.ConstantUtils;
import com.wf.smartcomm.server.util.IdUtils;
import com.wf.smartcomm.server.util.ImageUtils;
import com.wf.smartcomm.server.util.PushUtils;
import com.wf.smartcomm.server.util.StringUtil;

@Controller
@Scope("prototype")
public class AdAction extends BaseAction implements ModelDriven<Advertisement>{

	private Advertisement ad = new Advertisement();
	
	@Resource
	private AdService adServiceImpl;
	
	@Resource
	private ImageService imageServiceImpl;
	
	@Resource
	private ThumbImageService thumbServiceImpl;
	
	@Resource
	private VideoService videoServiceImpl;
	
	@Resource
	private UserService userServiceImpl;
	
	@Resource
	private UnitMachService unitMachService;
	
	private List<File> upload;  
    // /多个上传文件的类型集合  
    private List<String> uploadContentType;  
   // 多个上传文件的文件名集合  
    private List<String> uploadFileName;
    
	public List<File> getUpload() {
		return upload;
	}

	public void setUpload(List<File> upload) {
		this.upload = upload;
	}

	public List<String> getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(List<String> uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public List<String> getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(List<String> uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	
	public void add() throws Exception{
		User user = (User) session.getAttribute("loginUser");
		ad.setUser(user);
		ad.setVillage(user.getLoginVillage());
		
		if (!StringUtil.isEmpty(ad.getObjectId())) {
			adServiceImpl.update(ad);
			thumbServiceImpl.deleteAdImages(ad.getObjectId());
		} else {
			adServiceImpl.save(ad);
		}
		session.removeAttribute("ad");
		if (upload != null) {
			List<Image> images = new ArrayList<Image>();
			List<ThumbImage> thumbs = new ArrayList<ThumbImage>();
			List<Video> videos = new ArrayList<Video>();
			//String url = request.getRequestURL().substring(0, request.getRequestURL().lastIndexOf("jsp"))+"images/";
			String url = "http://"+PushUtils.pushConfig.getProperty("ImageServerIp");
			if (request.getServerPort() != 80) {
				url+=":"+request.getServerPort();
			}
			url+=request.getContextPath()+"/images/";
			for (int i = 0; i < upload.size(); i++) {
				if (uploadContentType.get(i).startsWith("image")) {
					String fileName = IdUtils.uuid()+".png";
					Image image = new Image();
					String path = request.getServletContext().getRealPath(
							"images");
					image.setUrl(url + fileName);
					image.setFileName(fileName);
					File des = new File(path + File.separator + fileName);
					FileUtil.copyFile(upload.get(i), des);
					BufferedImage bufferedImage = ImageIO.read(des);
					int width = bufferedImage.getWidth();   
					int height = bufferedImage.getHeight();
					System.out.println("width:"+width+" height:"+height);
					ThumbImage thumbImage = new ThumbImage();
					thumbImage.setFileName(fileName);
					thumbImage.setAd(ad);
					thumbImage.setUrl(url.replace("images", "thumbImages") +fileName);
					ImageUtils.getThumbnail(des.getAbsolutePath(),
							request.getServletContext().getRealPath(
									"thumbImages")+File.separator+fileName, 150, 150*height/width);
					images.add(image);
					thumbs.add(thumbImage);
				}else if(uploadContentType.get(i).startsWith("video")){
					Video video = new Video();
					String upName = uploadFileName.get(i);
					String fileName = IdUtils.uuid() + upName.substring(upName.lastIndexOf("."));
					video.setFileName(fileName);
					video.setUrl(url.replace("images", "videos") + fileName);
					video.setAd(ad);
					videos.add(video);
					String path = request.getServletContext().getRealPath(
							"videos");
					File des = new File(path + File.separator + fileName);
					FileUtil.copyFile(upload.get(i), des);
				}
			}
			
			if (images.size() > 0) {
				imageServiceImpl.save(images);
				thumbServiceImpl.save(thumbs);
			}
			
			if (videos.size() > 0) {
				videoServiceImpl.save(videos);
			}
		}
		printJsonData(200);
		Pusher pusher = PushUtils.getInstance();
		PushMessage msg = new PushMessage();
		msg.setPushType(ConstantUtils.PUSH_TYPE_AD_MSG);
		msg.setData(ad.getObjectId());
		unitMachService.listAllByVillage(user.getLoginVillage(), page);
		List<UnitMachine> unitMachines = (List<UnitMachine>) page.getDataList();
		for (UnitMachine unitMachine : unitMachines) {
			pusher.push0x20Message(unitMachine.getPushId().getBytes(), outGson.toJson(msg).getBytes());
		}
		pusher.close();
		Pusher clientPusher = PushUtils.getClientPusher();
		IApnsService service = PushUtils.getApnsService();
		userServiceImpl.listByVillage(user.getLoginVillage(), page);
		List<User> users = (List<User>) page.getDataList();
		for (User u : users) {
			if (u.getDeviceType().equals(ConstantUtils.DEVICE_TYPE_ANDROID)) {
				clientPusher.push0x20Message(u.getPushId().getBytes(), outGson.toJson(msg).getBytes());
			} else if(u.getDeviceType().equals(ConstantUtils.DEVICE_TYPE_APPLE)){
				Payload payload = new Payload();
				//payload.setAlert(ad.getSubject());
				payload.setBadge(0);
				//payload.setSound("default");
				payload.addParam("objectId", ad.getObjectId());
				payload.addParam("type", ConstantUtils.PUSH_TYPE_AD_MSG);
				service.sendNotification(u.getAppleToken(), payload);
			}
		}
		clientPusher.close();
	}
	
	public void list() throws Exception {
		String aoData = request.getParameter("aoData");
		String sEcho = "";
		String iDisplayStart = "";
		String iDisplayLength = "";
		String sSearch = "";
		User manager = (User) session.getAttribute("loginUser");
		JSONObject jo = new JSONObject(aoData);
		sEcho = jo.getString("sEcho");
		iDisplayStart = jo.getString("iDisplayStart");
		iDisplayLength = jo.getString("iDisplayLength");
		sSearch = jo.getString("sSearch");
		
		page.setBeginIndex(Integer.parseInt(iDisplayStart));
		page.setPageSize(Integer.parseInt(iDisplayLength));
		
		if (!StringUtil.isEmpty(sSearch)) {
			adServiceImpl.query(manager.getLoginVillage(),sSearch,page);
		} else {
			adServiceImpl.listByVillage(manager.getLoginVillage(), page);
		}
		
		int  initEcho = Integer.parseInt(sEcho)+1;
		int count = page.getTotalCount();
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("iTotalRecords", count);
		dataMap.put("sEcho",initEcho);
		dataMap.put("iTotalDisplayRecords", count);
		dataMap.put("aaData", page.getDataList());
		printJsonData(outGson.toJson(dataMap));
	}
	
/*     */   public String edit() throws Exception {
/* 222 */     this.ad = this.adServiceImpl.get(this.ad.getObjectId());

/* 230 */     request.setAttribute("ad", ad);
/* 231 */     return "edit";
/*     */   }
	
	public void delete() throws Exception{
		thumbServiceImpl.deleteAdImages(ad.getObjectId());
		adServiceImpl.delete(ad);
		printJsonData(200);
	}

	@Override
	public Advertisement getModel() {
		return ad;
	}
	
}
